package com.example.recall_application.mvp.ui.activity;


import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import android.widget.Switch;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.SPUtils;
import com.csipsimple.VoipUtil;
import com.example.recall_application.R;
import com.example.recall_application.app.Constants;
import com.example.recall_application.di.component.DaggerMainComponent;
import com.example.recall_application.mvp.contract.MainContract;
import com.example.recall_application.mvp.entity.Config;
import com.example.recall_application.mvp.entity.WxUserInfo;
import com.example.recall_application.mvp.presenter.MainPresenter;
import com.example.recall_application.utils.FileUtils;
import com.example.recall_application.utils.SystemUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/18/2019 14:46
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {
    @BindView(R.id.btn_go_setting)
    Button btnGoSetting;

    //private static final String APP_ID = "wx99ae37601ff59c45";
    BroadcastReceiver broadcastReceiver;
    @BindView(R.id.swh_sip)
    Switch swhSip;


    private IWXAPI api;
    MaterialDialog materialDialog;
    Timer timer;
    MyService.LocalBinder localBinder;
    WxUserInfo wxUserInfo;
    AlarmManager manager;
    public static int sip_flg = 0;
    PowerManager.WakeLock wakeLock;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            FileUtils fileUtils = new FileUtils();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/ HH:mm:ss");// HH:mm:ss
//获取当前时间
            Date date = new Date(System.currentTimeMillis());
            fileUtils.writeData(simpleDateFormat.format(date)+": process is yes"+"--uuid:"+SPUtils.getInstance().getString(Constants.uuid),"pdf_log.txt");
        }
    };


    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.uuid))) {
                        String u = SPUtils.getInstance().getString(Constants.uuid);
                        String p = SystemUtils.IDToKey(Constants.PSWKEY, u);
                        VoipUtil.startRegisterService(MainActivity.this, u, p, 300);
                        //Toast.makeText(MainActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    };


    ExecutorService executorService = Executors.newSingleThreadExecutor();

    ExecutorService executorService1 = Executors.newSingleThreadExecutor();
    private boolean logFirst = true;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void getWxLoginCode(SendAuth.Resp resp) {
        if (resp.errCode == 0) {
            String code = resp.code;
            mPresenter.getWxToken(code);
        } else {
            Toast.makeText(this, "微信未授权!", Toast.LENGTH_SHORT).show();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        btnGoSetting.setVisibility(View.VISIBLE);
        manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                localBinder = (MyService.LocalBinder) service;
                localBinder.getService().setForeground();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        },this.BIND_AUTO_CREATE);

        materialDialog = new MaterialDialog.Builder(this)
                .content("")
                .progress(true, -1)
                .canceledOnTouchOutside(true)
                .build();
        mPresenter.getPermission();
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void kill(String flag){
        if(flag.equals(Constants.KILL)){
            onDestroy();
        }
    }

    private void initWX(Context context) {
        api = WXAPIFactory.createWXAPI(context, Constants.APP_ID, true);
        // 将应用的appId注册到微信
        api.registerApp(Constants.APP_ID);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                api.registerApp(Constants.APP_ID);
            }
        };
        context.registerReceiver(broadcastReceiver, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
        //建议动态监听微信启动广播进行注册到微信
        String uuid = SPUtils.getInstance().getString(Constants.uuid);
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.uuid))) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            api.sendReq(req);
        } else {
            mPresenter.getConfig();
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.uuid))){
            finish();
            return;
        }
    }

    @Override
    public void showLoading() {
        //materialDialog.show();
    }

    @Override
    public void hideLoading() {
       // materialDialog.cancel();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    public void showConTacks(View view) {
        mPresenter.getPermission();
    }

    public void goSetting(View view) {
       Intent intent = new Intent(this,ConfigActivity.class);
       launchActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public void goLaiDian(View view) {
        try {
            Intent intent = new Intent();
            ComponentName comp;
            String brand = Build.BRAND;
            if (Build.BRAND.equals("OnePlus")) {
                comp = new ComponentName("com.android.dialer", "com.android.dialer.oneplus.activity.OPDialerSettingsActivity");
            } else {
                comp = new ComponentName("com.android.phone", "com.android.phone.CallFeaturesSetting");
            }
            intent.setComponent(comp);
            intent.setAction("android.intent.action.VIEW");
            startActivity(intent);
        } catch (Exception e) {
            e.toString();
        }

    }

    @Override
    public void setConfig(Config config) {

    }

    @Override
    public void setWxUserInfo(WxUserInfo wxUserInfo) {
        this.wxUserInfo = wxUserInfo;
        Intent intent = new Intent(this, WebActivity.class);
        launchActivity(intent);
    }

    @Override
    public void initWx() {
        initWX(this);
    }

    //记录日志
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    @Subscriber(mode = ThreadMode.MAIN)
    public void runLog(String flag) {
//        if(flag.equals(Constants.ALARMCLOCK)){
//
//            PowerManager pm = (PowerManager)getApplicationContext()
//                    .getSystemService(Context.POWER_SERVICE);
//            if(wakeLock == null){
//                wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
//                wakeLock.acquire(); // 唤醒手机
//            }else{
//               // wakeLock.release();
//                wakeLock.acquire();
//            }
//
//
////            new Thread(new Runnable() {
////                @Override
////                public void run() {
////                    FileUtils fileUtils = new FileUtils();
////                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/ HH:mm:ss");// HH:mm:ss
//////获取当前时间
////                    Date date = new Date(System.currentTimeMillis());
////                    fileUtils.writeData(simpleDateFormat.format(date)+": process is yes");
////                    //wakeLock.release();
////                }
// //           }).start();
//
//            executorService.submit(runnable);
//
//            AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//            long triggerAtTime = SystemClock.elapsedRealtime() + 3*60*1000;
//            Intent intent2 = new Intent(this, MyBroadcast.class);
//            PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0);
//            manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
//        }
       if(logFirst){
           //localBinder.getService().runLog();
           logFirst = false;
       }

    }

    @Override
    protected void onStop() {
        super.onStop();
        try{
            EventBus.getDefault().post(wxUserInfo);
        }catch (Exception e){

        }

    }

    public void quitLogin(View view) {
        api.unregisterApp();
        api.detach();
        unregisterReceiver(broadcastReceiver);
        SPUtils.getInstance().put(Constants.uuid, "");
        finish();
    }

    @Subscriber(mode = ThreadMode.MAIN)
    /**
     * 注册sip 模块
     * @param view
     */
    public void registerSip(String flag) {

        if(flag.equals(Constants.Sip_register)){
            if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.uuid))) {
               // Toast.makeText(this, "注册成功！", Toast.LENGTH_SHORT).show();

                //延迟5s注册
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        startTask();
                    }
                },5000);


            }
        }
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void changeFlag(String flag){
        if(flag.equals(Constants.Flag)){
            sip_flg = 1;
        }
    }

    /**
     * 之前每180秒注册一次sip 模块
     * 改为挂断后注册sip模块
     */
    private void startTask() {
        executorService1.submit(runnable1);
//        try {
//            manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//            long triggerAtTime = SystemClock.elapsedRealtime() + 180*1000;
//            Intent intent2 = new Intent(this, SIPBroadcast.class);
//            PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent2, 0);
//            manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
//        }catch (Exception e){
//            e.printStackTrace();
//        }




    }

    @Subscriber(mode = ThreadMode.MAIN)

    /**
     * 注销SIP模块
     * @param view
     */
    public void stopSip(String flag) {
        if(flag.equals(Constants.Sip_unregister)){
            //timer.cancel();
            sip_flg = 0;
            VoipUtil.stopRegisterService();
            //Toast.makeText(this, "注销成功！", Toast.LENGTH_SHORT).show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscriber(mode = ThreadMode.MAIN)
    public void getContacts(String flag){
        if(flag.equals(Constants.GET_CONTACTS)){
            mPresenter.initMainFunction();
        }
    }
}
